
package com.gitee.jmash.rbac.utils;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 随机密钥.
 *
 * @author chatGPT
 *
 */
public class RandomPasswordGenerator {
  private static final String UPPERCASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private static final String LOWERCASE_CHARS = "abcdefghijklmnopqrstuvwxyz";
  private static final String DIGITS = "0123456789";
  private static final String SPECIAL_CHARS = "!@#$%^&*()_+-=[]|,./?><";

  private static final String ALL_CHARS = UPPERCASE_CHARS + LOWERCASE_CHARS + DIGITS
      + SPECIAL_CHARS;

  /** 随机密码. */
  public static String generateRandomPassword() {
    StringBuilder password = new StringBuilder();
    Random random = new SecureRandom();

    // Generate the first 4 characters of the password
    boolean hasUppercase = false;
    for (int i = 0; i < 4; i++) {
      int randomIndex = random.nextInt(UPPERCASE_CHARS.length());
      password.append(UPPERCASE_CHARS.charAt(randomIndex));
      hasUppercase = true;
    }

    // Generate the next 2 characters of the password
    boolean hasLowercase = false;
    for (int i = 0; i < 4; i++) {
      int randomIndex = random.nextInt(LOWERCASE_CHARS.length());
      password.append(LOWERCASE_CHARS.charAt(randomIndex));
      hasLowercase = true;
    }

    // Generate the next 1 digit for the password
    boolean hasDigit = false;

    int randomIndex = random.nextInt(DIGITS.length());
    password.append(DIGITS.charAt(randomIndex));
    hasDigit = true;

    // Generate the next 1 special character for the password
    boolean hasSpecialChar = false;
    randomIndex = random.nextInt(SPECIAL_CHARS.length());
    password.append(SPECIAL_CHARS.charAt(randomIndex));
    hasSpecialChar = true;

    // Generate the remaining characters of the password

    while (password.length() < 8) {
      randomIndex = random.nextInt(ALL_CHARS.length());
      password.append(ALL_CHARS.charAt(randomIndex));
    }

    // Shuffle the characters of the password
    String shuffledPassword = shuffleString(password.toString());

    // Ensure that the password contains at least one character from each required
    // category
    if (!hasUppercase || !hasLowercase || !hasDigit || !hasSpecialChar) {
      return generateRandomPassword();
    }

    return shuffledPassword;
  }

  private static String shuffleString(String string) {
    char[] charArray = string.toCharArray();
    Random random = new SecureRandom();

    for (int i = charArray.length - 1; i > 0; i--) {
      int randomIndex = random.nextInt(i + 1);
      char temp = charArray[i];
      charArray[i] = charArray[randomIndex];
      charArray[randomIndex] = temp;
    }

    return new String(charArray);
  }

  public static void main(String[] args) {
    String password = generateRandomPassword();
    System.out.println(password);
  }
}
